# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(gplots)
library(Hmisc)
library(optparse)
library(ropls)
library(magrittr)
library(circlize)
library(tidyverse)

gg_color_hue <- function(n) {
  hues = seq(15, 375, length = n + 1)
  hcl(h = hues, l = 65, c = 100)[1:n]
}

getClassCols <- function(n) {
  inCols <- c()
  extraColors <- c("#CD0000", "#3A89CC", "#769C30", "#D99536", "#7B0078", "#BFBC3B", "#6E8B3D", "#00688B", "#C10077", "#CAAA76",
                   "#EEEE00", "#458B00", "#8B4513", "#008B8B", "#6E8B3D", "#8B7D6B", "#7FFF00", "#CDBA96", "#ADFF2F")
  orignalCols <- c(inCols, extraColors)
  on <- length(orignalCols)
  if (n <= on) {
    orignalCols[1:n]
  }else {
    ggCols <- gg_color_hue(n - on)
    c(orignalCols, ggCols)
  }
}


option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

method <- "pearson"
methodStr <- "Pearson"

data <- read.csv(str_c("QC_", methodStr, "_r_values.csv"), header = T, stringsAsFactors = F, row.names = 1)

parent <- "./"
fileName <- str_c(parent, "/QC_", methodStr, "_Chord.pdf")
pdf(fileName, width = 8, height = 8)
plotData <- data %>%
  abs() %>%
  as.matrix()

head(plotData)

if (nrow(plotData) >= 3) {
  diag(plotData) <- NA
  plotData[upper.tri(plotData)] <- NA
}

plotData

colorN <- length(rownames(plotData))
color <- getClassCols(colorN)
circos.par()
color
plotData
par(cex = 1.2, mar = c(0, 0, 0, 0))
chordDiagram(plotData, transparency = 0.7, grid.col = color, preAllocateTracks = list(track.height = 0.05))

circos.clear()
head(plotData)

dev.off()

